package com.anita.member.domain.model.member;

import com.anita.member.common.exception.BusinessException;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 密码值对象
 * @author qiu
 * @date 2025/10/17
 * @description
 */
public record Password (String value){

    public Password {
        if(value == null || value.isEmpty()){
            throw new BusinessException("会员密码不能为空");
        }
    }

    /**
     * 从原始密码生成加密后的密码
     */
    public static Password fromRaw(String rawPassword, PasswordEncoder passwordEncoder) {
        if (rawPassword == null || rawPassword.isEmpty()) {
            throw new BusinessException("原始密码不能为空");
        }
        if (rawPassword.length() < 6) {
            throw new BusinessException("密码长度不能少于6位");
        }
        return new Password(passwordEncoder.encode(rawPassword));
    }

    public static Password fromEncrypted(String encryptedPassword) {
        return new Password(encryptedPassword);
    }

    public boolean verify(String rawPassword, PasswordEncoder passwordEncoder) {
        return passwordEncoder.matches(rawPassword, value);
    }

    public String getValue() {
        return value;
    }
}
